﻿using FRMS.BUS;
using FRMS.DAL;
using FRMS.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace FRMS.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class OwnerController : ControllerBase
    {
        private JwtSettings _jwtSettings;
        IHttpContextAccessor _access;
        public OwnerController(IOptions<JwtSettings> jwtSettingsAccesser, IHttpContextAccessor access
         )
        {
            JwtSettings jwt = new JwtSettings();
            jwt.Audience = AppSettingsHelper.Configuration["JwtSettings:Audience"];
            jwt.Issuer = AppSettingsHelper.Configuration["JwtSettings:Issuer"];
            jwt.SecretKey = AppSettingsHelper.Configuration["JwtSettings:SecretKey"];
            _jwtSettings = jwt;
            _access = access;
        }

        /// <summary>
        /// 查询主卡类型
        /// </summary>
        [HttpPost]
        [Route("QueryMasterType")]
        public ResponseMessage QueryMasterType()
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                message = BUS.QueryOwnerType();
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "获取业主类型";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "获取业主类型异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 查询副卡类型
        /// </summary>
        [HttpPost]
        [Route("QuerySlaveType")]
        public ResponseMessage QuerySlaveType()
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                message = BUS.QuerySlaveType();
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "获取业主副卡类型";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "获取副卡类型异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 新建业主信息
        /// </summary>
        [HttpPost]
        [Route("AddOwner")]
        public ResponseMessage AddOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                if (ownerInfo.OwnerType == 2)
                {
                    message = BUS.AddProperty(ownerInfo);
                }
                else
                {
                    if (ownerInfo.ID > 0)
                    {
                        message = BUS.CopyOwner(ownerInfo.ID, ownerInfo.RoomID);
                    }
                    else
                    {
                        message = BUS.AddOwner(ownerInfo);
                    }
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "新增业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "新增业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 新建物业信息
        /// </summary>
        [HttpPost]
        [Route("AddProperty")]
        public ResponseMessage AddProperty(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = BUS.AddProperty(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "新增物业";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "新增业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 修改业主信息
        /// </summary>
        [HttpPost]
        [Route("UpdateOwner")]
        public ResponseMessage UpdateOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.MaxTime = Convert.ToDateTime(ownerInfo.MaxTime).ToString("yyyy-MM-dd HH:mm:ss");
                message = BUS.EditOwner(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "修改业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "修改业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 删除业主信息
        /// </summary>
        [HttpPost]
        [Route("DeleteOwner")]
        public ResponseMessage DeleteOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                message = BUS.DeleteOwner(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "删除业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "删除业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 查询主卡业主信息
        /// </summary>
        [HttpPost]
        [Route("QueryOwnerList")]
        public ResponseMessage QueryOwnerList(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = BUS.QueryOwneList(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "查询业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "查询业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 查询副卡业主信息
        /// </summary>
        [HttpPost]
        [Route("QueryOwnerByMaster")]
        public ResponseMessage QueryOwnerByMaster(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = BUS.QueryOwner(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "查询业主副卡";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "查询业主副卡信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 载入业主信息
        /// </summary>
        [HttpPost]
        [Route("LoadOwner")]
        public ResponseMessage LoadOwner(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                message = BUS.LoadOwner(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "载入业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "载入业主信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 一人多栋
        /// </summary>
        [HttpPost]
        [Route("OwnerCopy")]
        public ResponseMessage OwnerCopy(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                message = BUS.CopyOwner(ownerInfo.ID, ownerInfo.RoomID);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "载入业主";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "载入业主信息异常";
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 读取实体卡卡号
        /// </summary>
        [HttpPost]
        [Route("GetCardNO1")]
        public ResponseMessage GetCardNO1()
        {
            ResponseMessage message = new ResponseMessage();
            GetCardNO CardNO = new GetCardNO();

            //添加读卡操作过程
            UInt32 snr = 0;
            string error;
            //ushort type = 0;
            byte st;
            try
            {
                if (FSInvokeFun.RC500USB_init() != 0)
                {
                    message.errcode = 1;
                    message.errmsg = "读卡设备连接失败";
                    message.data = null;
                    message.total = 0;
                }
                else
                {
                    FSInvokeFun.RC500USB_config();
                    st = FSInvokeFun.RC500USB_anticoll(0, ref snr);
                    if (st != 0)
                    {
                        error = FSInvokeFun.CheckErr(st);
                        FSInvokeFun.RC500USB_exit();

                        message.errcode = 1;
                        message.errmsg = error;
                        message.data = null;
                        message.total = 0;
                    }
                    else
                    {
                        FSInvokeFun.RC500USB_exit();
                        CardNO.CardNO = snr.ToString();
                        message.errcode = 0;
                        message.errmsg = "";
                        message.data = CardNO;
                        message.total = 0;


                    }
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "读卡";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "读卡失败";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 查询访客信息
        /// </summary>
        [HttpPost]
        [Route("QueryVisitorList")]
        public ResponseMessage QueryVisitorList(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                ownerInfo.OwnerType = 4;
                message = BUS.QueryOwneList(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "查询访客";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "查询访客信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 新建访客信息
        /// </summary>
        [HttpPost]
        [Route("AddVisitor")]
        public ResponseMessage AddVisitor(OwnerInfo ownerInfo)
        {
            ResponseMessage message = new ResponseMessage();
            OwnerBUS BUS = new OwnerBUS();
            try
            {
                ownerInfo.projectID = Convert.ToInt32(_access.HttpContext.Session.GetString("ProjectID"));
                ownerInfo.OwnerType = 4;
                message = BUS.AddOwner(ownerInfo);
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "新增访客";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "新增访客信息异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 读取实体卡卡号
        /// </summary>
        [HttpPost]
        [Route("GetCardNO")]
        public ResponseMessage GetCardNO()
        {
            ResponseMessage message = new ResponseMessage();

            //创建socket
            try
            {
                GetCardNO card = new GetCardNO();
                string ip = _access.HttpContext.Connection.RemoteIpAddress.ToString();
                //LogHelper.Log(ip);
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //接收服务器的回馈
                byte[] readBuff = new byte[1024];
                //int port = Convert.ToInt32(CommVars.Configuration.GetSection("ICCardPort").Value);
                int port = Convert.ToInt32(AppSettingsHelper.Configuration["ICCardPort"]);
                //连接服务器
                clientSocket.Connect("localhost", port);

                //转码，转成0101010的格式
                byte[] sendBytes = Encoding.UTF8.GetBytes("ReadCardNo");

                //把二进制的消息发出去
                int kk = clientSocket.Send(sendBytes);
                int count = clientSocket.Receive(readBuff);
                string msg = Encoding.UTF8.GetString(readBuff, 0, count);
                ReturnMsg returnMsg = JsonConvert.DeserializeObject<ReturnMsg>(msg);
                if (returnMsg.code == 0)
                {
                    message.errcode = 0;
                    card.CardNO = returnMsg.message;
                    message.data = card;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = returnMsg.message;
                }

                clientSocket.Close();
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "读卡";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "读卡失败";
                message.data = null;
                message.total = 0;
            }
            return message;
        }

        /// <summary>
        /// 删除业主提示信息
        /// </summary>
        [HttpPost]
        [Route("PromptMessage")]
        public string PromptMessage(OwnerInfo ownerInfo)
        {
            string message;
            VoucherDAL da = new VoucherDAL();
            try
            {
                VoucherInfo voucher = new VoucherInfo();
                voucher.OwnerID = ownerInfo.ID;
                List<VoucherInfo> list = da.QueryVoucherList(voucher);
                List<VoucherInfo> infos = list.FindAll(delegate (VoucherInfo e) { return e.DeviceState == "离线"; });
                if (infos.Count > 0)
                {
                    string device_info = string.Empty;
                    foreach (var item in infos)
                    {
                        device_info += item.DeviceName + ",";
                    }
                    message = "设备" + device_info.Substring(0, device_info.Length - 1) + "处于离线状态，若强行删除会产生设备中凭证未清除的风险，是否继续?";
                }
                else
                {
                    message = "此操作将永久删除该用户及凭证, 是否继续?";
                }
            }
            catch (Exception e)
            {
                message = "此操作将永久删除该用户及凭证, 是否继续?";
            }
            return message;
        }

    }
}
